Skip to content

Add wasm-rquickjs:import-abort and name imported resource methods explicitly - #241

Merged
vigoo merged 3 commits into
mainfrom
gol-1053-import-abort
Nov 27, 2026
Merged

vigoo merged 3 commits into
mainfrom
gol-1053-import-abort

Conversation

@vigoo

@vigoo vigoo commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

This adds the built-in module wasm-rquickjs:import-abort. Its function withSignal(signal, fn) lets JavaScript cancel the async imports that fn starts. This change also gives each imported resource method an explicit JavaScript name, so the runtime name matches the name in the generated declarations.

Why. In Golem (GOL-1053), an agent-to-agent call is now one async invoke-and-await import. When a TypeScript caller aborts the call with an AbortSignal, or an Effect fiber is interrupted, the call must be withdrawn on a best-effort basis. To withdraw an async import, the guest must drop its subtask. Before this change, JavaScript had no way to do that: a promise cannot be cancelled, and the generated bridges kept the import future until it completed.

Walkthrough: how cancellation works

The problem

An async import returns a promise. A promise has no "stop" button: once JavaScript calls the import, the runtime keeps the import running until it completes, even if nobody waits for the result any more. The host never learns that the caller gave up.

The idea: a "current signal"

withSignal(signal, fn) makes signal the current signal while fn runs. Every async import that is called during that time picks up the current signal. When the signal aborts, each import that picked it up stops:

  • its promise rejects with signal.reason, and
  • the runtime drops the import, which cancels its subtask. The host stops the call, or learns that its caller stopped waiting.
import { withSignal } from 'wasm-rquickjs:import-abort';
import { fetchReport } from 'example:reports/api'; // any async import

const controller = new AbortController();
const report = withSignal(controller.signal, () => fetchReport('q3'));

setTimeout(() => controller.abort(new Error('too slow')), 1000);

await report; // the report, or Error('too slow') after one second

Any object with aborted, reason, addEventListener and removeEventListener works as the signal, so a plain AbortSignal is enough.

What happens, step by step

 JavaScript                     generated import bridge                host
 ----------                     -----------------------                ----
 withSignal(signal, () =>
   fetchReport('q3'))
        |
        | 1. signal becomes current
        v
 fetchReport('q3') ---------->  2. remembers the current signal
 <---- promise ----------------
 withSignal returns;
 the previous signal is current again

                                when the runtime first runs the import:
                                3. checks signal.aborted, then adds
                                   an "abort" listener
                                4. starts the import ----------------> subtask starts
                                   (the future runs in an Abortable)

        ... later ...

 controller.abort(reason) --->  5. the listener fires
                                6. the Abortable drops the import ---> subtask cancelled
                                7. removes the listener
 <---- promise rejects with reason

If the import finishes first, steps 5 and 6 never happen: the bridge removes the listener and the promise resolves with the result. The listener is removed in every case, so a signal that is used for many imports does not collect listeners.

When the abort comes, and what you get

The signal aborts… The import The promise
before the call (signal.aborted is already true) never starts rejects with signal.reason
after the call, before the runtime first polls the import never starts rejects with signal.reason
while the host runs the import is dropped; its subtask is cancelled rejects with signal.reason
after the import finished is not affected keeps its result

Only the synchronous part of fn counts

The signal is current only while fn runs synchronously. An async function runs synchronously up to its first await, so only the imports before that await pick up the signal:

await withSignal(signal, async () => {
  const a = await first();     // picks up the signal
  return await second(a);      // does NOT: it starts after an await
});
withSignal(signal, async () => {
  ┌─ signal is current ───────────────┐
  │  first()        → takes signal    │
  └───────────────────────────────────┘ ← withSignal returns at the first await
  await ...
  second(a)         → no signal
})

To cover every import, wrap each one:

const a = await withSignal(signal, () => first());
const b = await withSignal(signal, () => second(a));

Nesting

An inner withSignal replaces the signal only for its own fn. When it returns or throws, the outer signal is current again. null or undefined means "no signal".

withSignal(outer, () => {
  importA();                          // outer
  withSignal(inner, () => importB()); // inner
  importC();                          // outer again
  withSignal(null, () => importD());  // no signal
});

Overlapping invocations

The current signal is one value per JavaScript runtime. With overlapping invocations, one runtime runs several invocations at the same time, and each of them can make an agent call with its own signal. So why can't the signals get mixed up?

The answer: the current signal lives only for a moment, but each import remembers its own copy for as long as it runs.

How long it lasts What it is for
The current signal Only while fn runs synchronously: microseconds Hands the signal to the import bridge, like a hidden extra argument
The signal an import remembers From the call until the import finishes or is aborted: seconds or minutes Its abort listener cancels exactly this import

The bridge reads the current signal once, when JavaScript calls the import. It never reads the current signal again for that import. Each import also gets its own abort listener, which cancels only that import.

Here are two invocations that overlap:

// invocation A
const a = new AbortController();
const resultA = withSignal(a.signal, () => rpc.invokeAndAwait('slow', input));

// invocation B starts while A still waits
const b = new AbortController();
const resultB = withSignal(b.signal, () => rpc.invokeAndAwait('fast', input));

a.abort(new Error('A gave up')); // cancels only A's call; B goes on
time ───────────────────────────────────────────────────────────────────────▶

current signal:   [a]           [b]            (empty the rest of the time)
                   │             │
invocation A:      call ── remembers a ──────────── a aborts ──▶ A's call cancelled
invocation B:                  call ── remembers b ─────────────────────────▶ B's result
  • withSignal(a.signal, …) makes a current, the bridge of A's import remembers a, and withSignal makes the previous signal current again before it returns.
  • When B runs, the current signal is empty again, so B's withSignal sets b. A's import does not see this, because it already has a.
  • a.abort() calls only the listener of A's import. B's import has no listener on a.

This is safe because JavaScript runs one piece of code at a time. While fn runs, no other invocation's code can run, so no other invocation can see or change the current signal. Invocation B can only run after A reached an await, and by then withSignal already restored the previous signal. The custom invocation context uses the same rule: each import is attributed to the scope that is current when JavaScript calls it.

The test p3_import_abort_cancels_the_signalled_imports checks this with real overlapping export calls on one component instance. It starts three overlapping calls at the same time. Each call uses its own signal and waits in a host call. When all three host calls run, it aborts the signal of the second call. The second host call is cancelled. The first and third finish afterwards with their results. A runtime that cancels the wrong import fails this case, for example one where an abort cancels the import that started last.

Arguments

  • Plain arguments and resources. The runtime converts them when the import is called. If the import never starts, the runtime drops them, so an owned resource that was passed to the import is destroyed.
  • stream and future arguments. With an already aborted signal, the runtime does not read the JavaScript source at all. If the abort comes later, the runtime closes the stream and calls return() on the source's iterator, so a finally block in a generator runs:
async function* rows() {
  try {
    yield 1;
    yield 2;
  } finally {
    console.log('source closed');   // runs when the import is aborted
  }
}

const uploaded = withSignal(controller.signal, () => upload(rows()));
controller.abort();                 // the host stops reading; 'source closed' is logged

How Golem uses it

The Golem TypeScript SDK makes an agent-to-agent call with one async import. It passes the caller's AbortSignal through withSignal:

// golem-ts-sdk, awaited agent call
completed = await withSignal(signal, () => rpc.invokeAndAwait(method, input, scope));
 caller aborts ──> wasm-rquickjs drops ──> Golem sees the subtask cancelled
                   invoke-and-await          ├─ remote invocation not started yet: it is withdrawn
                                             └─ already running: it keeps running,
                                                the caller only stops waiting

Awaiting the result of an invocation handle (handle.awaitResult({ signal })) uses the same mechanism on the handle's await_() method. There, dropping the import only stops the wait; the invocation itself goes on. The Effect SDK aborts the signal when the fiber is interrupted, so interrupting an Effect cancels the call in the same way.

Where the code is

Part File
withSignal (JavaScript) skeleton/src/builtin/import_abort.js
Current signal: enter / leave, and the bridge helpers skeleton/src/internal/import_abort.rs
Listener plus Abortable around the import future (the existing helper fetch also uses) skeleton/src/builtin/abort_signal.rs (with_abort_signal)
Generated bridges that call the helpers src/imports.rs
TypeScript declarations src/import_abort.d.ts
Tests and example component (including the overlapping calls) tests/p3_import_abort.rs, examples/p3/import-abort

Reference: the changes in detail

withSignal (skeleton/src/builtin/import_abort.{js,rs}, skeleton/src/internal/import_abort.rs, builtin/mod.rs, internal/runtime_services.rs)

  • withSignal(signal, fn) calls fn and returns its result. While fn runs synchronously, signal is the current signal. Each async import that starts in that time takes the signal.
  • When the signal aborts, the import's promise rejects with signal.reason, and the bridge drops the import future. Dropping the future cancels the subtask.
  • When the signal is already aborted, each import that fn calls rejects at once and does not start.
  • An import that finished before the abort keeps its result.
  • An import that starts after an await inside fn does not take the signal, because the signal is current only during the synchronous part of fn.
  • A nested withSignal restores the outer signal when it returns or throws. A top-level call restores "no signal".

Generator (src/imports.rs)

  • Each async import bridge returns an abortable import: freestanding functions, resource methods, static resource functions, and functions with future or stream parameters.
  • For future and stream parameters, the bridge checks for an already aborted signal before it lowers any argument, so it reads nothing from the JavaScript source. It adds the abort listener only after all arguments are converted, so a conversion error leaves no listener on the signal. After it adds the listener, it checks signal.aborted again, because a signal-like wrapper can abort inside addEventListener before it registers the listener. In that case it removes the listener and rejects without starting the import, as the other bridges already do.
  • The other arguments are converted when the bridge is called. If the import does not start, the bridge drops them, so owned resources passed to it are destroyed. The README says so.

Resource method names (src/imports.rs). This is a breaking change for plain JavaScript callers.

  • Before: rquickjs rename_all = "camelCase" named the methods of imported resources. The .d.ts generator uses escape_js_ident(to_lower_camel_case(name)). The two rules gave different names for some methods. For example, the method %await was await at runtime but await_ in the .d.ts, so a TypeScript call of await_() failed with "not a function".
  • After: each imported resource method has #[qjs(rename = ...)] with the .d.ts rule. The names that change:
    • Methods whose names are JavaScript or Rust keywords: delete_, new_, await_.
    • Names with a digit followed by a letter inside one word: sha256Sum becomes sha256sum.

TypeScript declarations (src/typescript.rs, src/import_abort.d.ts)

  • generate-dts writes wasm-rquickjs-import-abort.d.ts for a world with async imports.

Tests

  • New example examples/p3/import-abort and test tests/p3_import_abort.rs. They cover:
    • each bridge shape, with an abort before the call, before the first poll, while lowering a future or stream argument, and while the host runs the import;
    • a JavaScript stream source: it is closed (return() called) when the host has not read it yet, and it is not read at all when the signal is already aborted;
    • a finished import that keeps its result;
    • fn throwing, at the top level and nested;
    • overlapping exported calls on one instance, each with its own signal: aborting one signal cancels only that call's host call, while the other calls still run;
    • listener counts: one listener while the import runs, none after it settles or aborts, and none after an argument conversion error;
    • a signal that aborts inside addEventListener: no host call starts and no listener stays, for both bridge kinds;
    • a resource method named %await, called as await_(). This case fails without the rename fix.
  • New goldenfile tests/goldenfiles/generated_types_all-golem-imports_wasm-rquickjs-import-abort.d.ts.
  • README section for wasm-rquickjs:import-abort.

Checks

  • CI: the generation suite of test-p3 now also runs --test p3_import_abort.
  • On this branch: cargo test --test p3_import_abort --test dts (3 and 87 tests pass), cargo fmt --check, cargo clippy --all-targets -- -Dwarnings, and tools/check-skeleton-clippy.sh (default and maximal lanes).
  • Before the rebase onto main: p3_async_values, p3_generation, p3_custom_invocation_context and p3_exported_resource pass.
  • In Golem, with a local build of this change: the TypeScript and Effect SDK tests, the worker-executor tests of TypeScript invocation handles, the Effect caller harness, and the Scala trigger integration test.
  • Not run: p3_invocation_tasks (fork lane), the full runtime suite and node_compat.

skeleton/src/builtin/mod.rs still has three rustfmt differences that are also on main. This change does not touch them.

The Golem side, which uses withSignal in the TypeScript and Effect SDKs and calls await_() in the Scala SDK, waits for a release with this change.

vigoo and others added 2 commits November 26, 2026 07:53
…licitly

withSignal(signal, fn) lets JavaScript cancel the async imports that fn
starts: an abort rejects the import and drops it, which cancels its
subtask. Imported resource methods now get an explicit JavaScript name
from the same rule as the generated declarations, so %await is await_.

Amp-Thread-ID: https://ampcode.com/threads/T-01a20968-e35a-756a-a2f3-deaba79311e3
Co-authored-by: Amp <amp@ampcode.com>
Three overlapping exported calls each pass their own signal to
withSignal and wait in a host call. Aborting the signal of the second
call cancels only its host call; the first and third finish afterwards.

Co-authored-by: Amp <amp@ampcode.com>
Amp-Thread-ID: https://ampcode.com/threads/T-01a20968-e35a-756a-a2f3-deaba79311e3
options.set("once", true)?;
let add: rquickjs::Function = signal.get("addEventListener")?;
add.call::<_, ()>((This(signal.clone()), "abort", callback.clone(), options))?;
Ok(ArmedImportAbort::Armed(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we recheck signal.aborted after registering the listener, as with_abort_signal does? An AbortSignal-like wrapper can abort before delegating to the real addEventListener, so this path misses the event and starts the deferred import anyway. Please remove the listener and reject with signal.reason in that case, with a regression checking that no host call starts.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 8f2559b. arm_deferred_import_abort now checks signal.aborted again after addEventListener. When the signal aborted, it removes the listener and returns Aborted, so the bridge rejects with signal.reason and starts no import. The lowered stream readers are dropped, as in the existing abort-while-lowering path.

Regression: abortingOnListen in examples/p3/import-abort is a signal wrapper that aborts its inner signal before it passes the listener on. The test checks for both bridge kinds (wait and the deferred consume) that the promise rejects with the reason, no start: record exists, and no listener stays. For the deferred case it also checks that the JS source is closed. Without the fix, the deferred case recorded start:on-listen-deferred and ran the full 10 s host call.

Comment thread tests/p3_import_abort.rs
}

#[test]
fn p3_import_abort_cancels_the_signalled_imports() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we add --test p3_import_abort to a P3 CI lane? The current explicit test lists omit this target, so the new cancellation and overlapping-call regressions are not exercised by the green CI run.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 8f2559b: the generation suite of test-p3 now runs --test p3_generation --test p3_exported_resource --test p3_import_abort. The test needs no fork-only fix, so it runs on the stock wasmtime like the other P3 tests in that lane.

…abort in CI

A signal-like wrapper can abort inside addEventListener before it
registers the listener. The deferred import bridge now checks aborted
again after it added the listener; when the signal aborted, it removes
the listener and rejects without starting the import, as
with_abort_signal already does for the other bridges.

The test-p3 generation lane now runs p3_import_abort.

Co-authored-by: Amp <amp@ampcode.com>
Amp-Thread-ID: https://ampcode.com/threads/T-01a20968-e35a-756a-a2f3-deaba79311e3

@noise64 noise64 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both earlier findings are verified fixed in source and the exact-head CI regression tests. Looks good.

@vigoo
vigoo merged commit a57ed89 into main Nov 27, 2026
31 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants